import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import TypingPractice from './components/TypingPractice.vue'
import TypingTutorial from './components/TypingTutorial.vue'
import WubiTutorial from './components/WubiTutorial.vue'
import Rank from './components/Rank.vue'
import About from './components/About.vue'
import Faq from './components/Faq.vue'
import TypingGames from './components/TypingGames.vue'
import TypingGameRain from './components/TypingGameRain.vue'
import TypingGameChallenge from './components/TypingGameChallenge.vue'
import TypingGameQuote from './components/TypingGameQuote.vue'
import Login from './components/Login.vue'
import Register from './components/Register.vue'
import store from './store'

Vue.config.productionTip = false
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/practice' },
  { path: '/practice', component: TypingPractice },
  { path: '/tutorial', component: TypingTutorial },
  { path: '/wubi', component: WubiTutorial },
  { path: '/rank', component: Rank },
  { path: '/about', component: About },
  { path: '/faq', component: Faq },
  { path: '/games', component: TypingGames },
  { path: '/games/rain', component: TypingGameRain },
  { path: '/games/challenge', component: TypingGameChallenge },
  { path: '/games/quote', component: TypingGameQuote },
  { path: '/login', component: Login },
  { path: '/register', component: Register }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

const protectedRoutes = [
  '/games',
  '/games/rain',
  '/games/challenge',
  '/games/quote'
]

router.beforeEach((to, from, next) => {
  if (protectedRoutes.some(path => to.path === path || to.path.startsWith(path + '/'))) {
    if (!store.state.user.isLogin) {
      next({ path: '/login', query: { redirect: to.fullPath } })
      return
    }
  }
  next()
})

new Vue({
  router,
  store,
  render: function (h) { return h(App) },
}).$mount('#app')
